#include <sys/time.h>
#include <signal.h>
#include <stdio.h>

#include <clock.h>

volatile unsigned long ticks;

/**
 * virtual timer handler
 */
void
clock_handler (int dummy)
{
	ticks ++;
	if (ticks % 100 == 0)
		printf ("100 ticks\n");
}

/**
 * register virtual timer handler and initialize virtual timer with default interval
 * @return 0 on success, -1 on error when set interval, -2 on error when register timer handler
 */
int
clock_init (void) 
{
	printf ("++ setup timer interrupts\n");
	if (signal (SIGVTALRM, clock_handler) == SIG_ERR)
		return -2;
			
	return clock_set_interval (DEFAULT_TV_SEC, DEFAULT_TV_USEC);
}

/**
 * set virtual timer interval and restart the timer
 * @param sec interval in seconds
 * @param usec interval in microseconds
 * @return 0 on success
 */
int
clock_set_interval (long sec, long usec) 
{
	struct itimerval interval = ((struct itimerval) {{sec, usec}, {sec, usec}});
	return setitimer (ITIMER_VIRTUAL, &interval, NULL);
}

